﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using IFDB.Models.Contexts;
using IFDB.Models.Tables;
using IFDB.ResourceLibrary;
using IFDB.ViewModels.Foundation;
using IFDB.ViewModels.PartialViewModels.Interfaces;

namespace IFDB.ViewModels.PartialViewModels
{
    public class TeamMatchListViewModel : BaseViewModel, ITeamMatchListViewModel
    {
        #region Constructor
        public TeamMatchListViewModel(Team team, DateTime startDate, DateTime endDate)
        {
            this.Team = team;
            this.StartDate = startDate;
            this.EndDate = endDate;
        }
        #endregion

        #region Fields
        private IEnumerable<Match> teamMatchList = null;
        #endregion

        #region ITeamMatchListViewModel implementation
        public Team Team { get; set; }
        public DateTime StartDate { get; set; }
        public DateTime EndDate { get; set; }

        public IEnumerable<Match> TeamMatchList
        {
            get
            {
                if (teamMatchList == null)
                    using (IFDBContext db = new IFDBContext())
                        teamMatchList = (from m in db.Matches
                                             .Include(m => m.Competition)
                                             .Include(m => m.Venue)
                                             .Include(m => m.Team1.TeamNames)
                                             .Include(m => m.Team2.TeamNames)
                                             .Include(m => m.AppearanceEvents.Select(a => a.Person))
                                         where (m.Team1Id == Team.TeamId || m.Team2Id == Team.TeamId)
                                         && m.MatchDate >= StartDate && m.MatchDate <= EndDate
                                         && (m.MatchStatus == MatchStatus.ScoreOnly || m.MatchStatus == MatchStatus.FullMatch)
                                         orderby m.MatchDate descending
                                         select m).ToList();

                return teamMatchList;
            }
        }
        #endregion
    }
}
